package Model.Matchmaking;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import DBAccess.DBAccess;
import MailGenerator.Mailer;
import Model.User;

public class Newsletter {

	private static int numdays = 0;
	public static void sendEmails(){
		PreparedStatement ps = null;
		ResultSet rs = null;
		if (numdays % 6 ==0 )
			try{
				ps = DBAccess.con.prepareStatement("SELECT userID FROM personaldb WHERE newsletterflag=1");
				rs = ps.executeQuery();
				while(rs.next()){
					int userid = rs.getInt(1);
					ArrayList<Match> matches = Match.getMatches(userid);
					String email = "Here are this week's top 10 matches\n";
					StringBuffer buf = new StringBuffer();
					for(int i=0; i<matches.size(); i++){
						Match match = matches.get(i);
						buf.append(User.getName(match.getUserID())+" "+match.getScore()+" points.\n");
					}
					email += buf.toString();
					
					Mailer.sendMail(User.getEmail(userid), "This week's matches", email);
				}
			} catch(Exception e){
				e.printStackTrace();
			}
		try{
			ps = DBAccess.con.prepareStatement("SELECT userID FROM personaldb WHERE newsletterflag=2");
			rs = ps.executeQuery();
			while(rs.next()){
				int userid = rs.getInt(1);
				ArrayList<Match> matches = Match.getMatches(userid);
				String email = "Here are today's top 10 matches\n";
				StringBuffer buf = new StringBuffer();
				for(int i=0; i<matches.size(); i++){
					Match match = matches.get(i);
					buf.append(User.getName(match.getUserID())+" "+match.getScore()+" points.\n");
				}
				email += buf.toString();
				
				Mailer.sendMail(User.getEmail(userid), "Today's matches", email);
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		DBAccess.close(ps, rs);
		numdays++;
	}
	  public static int getNewsletterFlag(int userID){
		  PreparedStatement ps = null;
		  ResultSet rs = null;
		  int flag = 0;
		  try{
			  ps = DBAccess.con.prepareStatement("SELECT newsletterflag FROM personaldb WHERE userID=?");
			  ps.setInt(1, userID);
			  rs = ps.executeQuery();
			  
			  if(rs.next())
				  flag = rs.getInt(1);
			  DBAccess.close(ps,rs);
		  } catch(Exception e){
			  e.printStackTrace();
		  }
		  return flag;
	  }
}
